package se.jocke.nb.log.internal;

import com.google.common.base.Charsets;
import com.google.common.base.StandardSystemProperty;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openide.modules.Places;
import org.openide.util.lookup.ServiceProvider;
import se.jocke.nb.log.HistoryManager;

@ServiceProvider(service = HistoryManager.class)
public class HistoryManagerImpl implements HistoryManager {

    private static final Deque<File> HISTORY = new ConcurrentLinkedDeque<File>();

    private static final Logger LOG = Logger.getLogger(HistoryManagerImpl.class.getName());

    private static final String HISTORY_FILE = "log-history.txt";

    private static final int HISTORY_LENGTH = 10;

    @Override
    public Set getHistory() {

        File doc = new File(Places.getUserDirectory(), HISTORY_FILE);

        if (doc.exists() && HISTORY.isEmpty()) {
            try {
                for (String path : Files.readLines(doc, Charsets.UTF_8)) {
                    HISTORY.add(new File(path));
                }
            } catch (IOException ex) {
                LOG.log(Level.SEVERE, "Failed to read history file", ex);
            }
        }
        return new LinkedHashSet(HISTORY);
    }

    @Override
    public void addToHistory(File file) {

        File doc = new File(Places.getUserDirectory(), HISTORY_FILE);

        if (!doc.exists()) {
            try {
                doc.createNewFile();
            } catch (IOException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }

        if (HISTORY.contains(file)) {
            HISTORY.remove(file);
        }

        HISTORY.addFirst(file);

        if (HISTORY.size() > HISTORY_LENGTH) {
            HISTORY.removeLast();
        }

        StringBuilder builder = new StringBuilder();

        for (File path : HISTORY) {
            builder.append(path.getPath()).append(StandardSystemProperty.LINE_SEPARATOR.value());
        }
        
        LOG.log(Level.INFO, "Updating history file {0}", doc);

        try {
            Files.write(builder.toString().getBytes(), doc);
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }

    }

}
